using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using NP.Enterprise.Utils.ApiResult;
using System;
using Volo.Abp.AspNetCore.Mvc.ExceptionHandling;
using Volo.Abp.Authorization;
using Volo.Abp.Validation;

namespace NP.BPMReportPlatform.Filters
{
    public class CustomExceptionFilter : AbpExceptionFilter
    {
        private readonly ILogger<CustomExceptionFilter> _logger;

        public CustomExceptionFilter(ILogger<CustomExceptionFilter> logger)
        {
            _logger = logger;
        }
        
        protected override bool ShouldHandleException(ExceptionContext context)
        {
            var obj_code = context.Exception.Data["error_code"];

            int code = obj_code == null ? 500 : Convert.ToInt32(obj_code);

            if (code == 500)
            {
                //判断校验异常
                if (context.Exception is AbpValidationException)
                {
                    //code = 400;//如果是校验错误则code为400
                    var error = context.Exception as AbpValidationException;

                    var mess = string.Join("|", error.ValidationErrors);

                    context.Result = new ObjectResult(ApiResult.Failed(mess, code));
                }
                //此处可以添加多个else if 来实现对于特定异常的再次封装
                else if (context.Exception is AbpAuthorizationException)
                {
                    //判断授权异常
                    //context.HttpContext.Response.StatusCode = 200;
                    context.Result = new ObjectResult(ApiResult.Failed("权限验证失败：" + context.Exception.Message, code));
                }
                else
                {
                    var mess = context.Exception.Message.IsNullOrWhiteSpace() ? "服务器忙请稍后再试" : context.Exception.Message.ToString();
                    context.Result = new ObjectResult(ApiResult.Failed(mess, code));
                }
                _logger.LogException(context.Exception);
            }
            else
            {
                var obj_mess = context.Exception.Data["error_mess"];
                var mess = obj_mess == null ? "服务器忙请稍后再试" : obj_mess.ToString();
                context.Result = new ObjectResult(ApiResult.Failed(mess, code));
                _logger.LogException(context.Exception);
            }

            if (context.HttpContext.Response.StatusCode != 200)
            {
                context.HttpContext.Response.StatusCode = 200;
            }

            return false;
        }
    }
}